package com.wfc.util.Filter;


import com.wfc.entity.User;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class loginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        System.out.println("拦截");

        Cookie[] cookies = req.getCookies();
        String username = null;
        String password = null;;
        if(cookies != null) {
            //遍历cookie
            for(Cookie cookie : cookies) {
                if("username".equals(cookie.getName())) {//看cookie的name是不是与cookie的名字匹配
                    username = cookie.getValue();
                }else if("password".equals(cookie.getName())){
                    password = cookie.getValue();
                }
            }
        }
        if(username != null && password != null ) {
            filterChain.doFilter(req,resp);
        }else {
            resp.sendRedirect("http://localhost:8080/login.jsp");
        }
//        filterChain.doFilter(req,resp);

    }

    @Override
    public void destroy() {

    }
}
